<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
    <!-- <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">-->
    <title>百度逗比表情列表</title>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script>
    function onDraw() {

        var canvas = document.getElementById("myCanvas");
        var ctx = canvas.getContext("2d");
        var fw = 30;
        var fh = 30;
        var fPadding = 10;
        var xCount = 10;
        var yCount = Math.ceil(56 / 10);
        var frw = (fw + fPadding * 2);//实际占位宽
        var frh = (fh + fPadding * 2);
        canvas.width = frw * xCount;
        canvas.height = frh * yCount;

        var baseLink = "https://tb2.bdstatic.com/tb/editor/images/face/i_f";
        var imgType = ".png";


        //一排排绘制
        for (var j = 0; j < yCount; j++) {//y轴

            for (var i = 0; i < xCount; i++) {//x轴

                var count = j * xCount + i + 1;

                var iStr = count + "";
                iStr.length === 1 ? (iStr = "0" + iStr) : false;
                var faceLink = baseLink + iStr + imgType;
                // console.log(faceLink);

                var img = new Image();
                // img.crossorigin="anonymous";//
                img.setAttribute("crossOrigin",'Anonymous');
                // 跨域的图片会污染画布，使用toBlob(),toDataURL(),getImageData()等方法会报错：Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
                img.src = faceLink;

                drawImg(img, i * frw + fPadding, j * frh + fPadding);
            }

        }

        function drawImg(img, x, y) {

            img.onload = function (e) {
                ctx.drawImage(img, 0, 0, img.width, img.height, x, y, fw, fh)
                genBase64Img(img);
            }
        }

        var base64Imgs = [];
        function genBase64Img(img) {
            var url = img.currentSrc;
            var canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0,0,img.width,img.height);
            // 图片格式，质量
            var dataUrl = canvas.toDataURL('image/png', 1);
            base64Imgs.push(JSON.stringify({url:url,src:dataUrl}));
        }


        //应检测所有图片转换完毕后执行
        setTimeout(function(){
            var elPre = document.createElement("pre");
            elPre.innerText = (base64Imgs+"").replace(/\}\,/g,"},\n");
            document.body.appendChild(elPre);

        },1500);
    }

    onDraw();

</script>
</body>
</html>